"""
Example client for PaddleOCR FastAPI service
"""
import requests
import json
from pathlib import Path
import argparse


class OCRClient:
    """Client for PaddleOCR API"""
    
    def __init__(self, base_url="http://localhost:8000"):
        self.base_url = base_url
    
    def health_check(self):
        """Check if service is healthy"""
        response = requests.get(f"{self.base_url}/health")
        return response.json()
    
    def process_video(self, video_path, sample_rate=1):
        """
        Process video and get OCR results as JSON
        
        Args:
            video_path: Path to video file
            sample_rate: Process every Nth frame
        
        Returns:
            Dictionary with OCR results
        """
        with open(video_path, "rb") as f:
            files = {"file": (Path(video_path).name, f, "video/mp4")}
            response = requests.post(
                f"{self.base_url}/process-video",
                files=files,
                params={"sample_rate": sample_rate}
            )
        
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"Error: {response.status_code} - {response.text}")
    
    def process_video_with_output(self, video_path, output_path, sample_rate=1):
        """
        Process video and save output video with OCR results
        
        Args:
            video_path: Path to input video file
            output_path: Path to save output video
            sample_rate: Process every Nth frame
        """
        with open(video_path, "rb") as f:
            files = {"file": (Path(video_path).name, f, "video/mp4")}
            response = requests.post(
                f"{self.base_url}/process-video-with-output",
                files=files,
                params={"sample_rate": sample_rate}
            )
        
        if response.status_code == 200:
            with open(output_path, "wb") as f:
                f.write(response.content)
            print(f"Output video saved to: {output_path}")
        else:
            raise Exception(f"Error: {response.status_code} - {response.text}")
    
    def extract_text_from_video(self, video_path, sample_rate=1):
        """
        Extract all text from video
        
        Args:
            video_path: Path to video file
            sample_rate: Process every Nth frame
        
        Returns:
            List of all detected texts
        """
        results = self.process_video(video_path, sample_rate)
        all_texts = []
        
        for frame in results["frames"]:
            for text in frame["texts"]:
                if text and text not in all_texts:
                    all_texts.append(text)
        
        return all_texts


def main():
    parser = argparse.ArgumentParser(description="PaddleOCR API Client")
    parser.add_argument("--url", default="http://localhost:8000", help="API base URL")
    parser.add_argument("--video", required=True, help="Path to video file")
    parser.add_argument("--output", help="Output video path (if not specified, only JSON results)")
    parser.add_argument("--sample-rate", type=int, default=1, help="Process every Nth frame")
    parser.add_argument("--extract-text", action="store_true", help="Extract all unique texts")
    
    args = parser.parse_args()
    
    client = OCRClient(args.url)
    
    # Check health
    print("Checking service health...")
    health = client.health_check()
    print(f"Service status: {health['status']}")
    print(f"Models loaded: {health['models_loaded']}\n")
    
    if not health['models_loaded']:
        print("Error: Models not loaded!")
        return
    
    # Process video
    print(f"Processing video: {args.video}")
    print(f"Sample rate: {args.sample_rate}\n")
    
    if args.output:
        # Process with output video
        client.process_video_with_output(args.video, args.output, args.sample_rate)
    
    # Get JSON results
    results = client.process_video(args.video, args.sample_rate)
    
    # Print summary
    print("=" * 60)
    print("Processing Summary")
    print("=" * 60)
    print(f"Total frames: {results['video_info']['total_frames']}")
    print(f"FPS: {results['video_info']['fps']}")
    print(f"Duration: {results['video_info']['duration_seconds']:.2f}s")
    print(f"Frames processed: {results['processing_info']['total_frames_processed']}")
    print()
    
    # Print frame results
    print("=" * 60)
    print("Frame Results")
    print("=" * 60)
    for frame in results["frames"][:5]:  # Show first 5 frames
        print(f"\nFrame {frame['frame_number']} (Time: {frame['timestamp']:.2f}s)")
        print(f"  Detected texts: {len(frame['texts'])}")
        for text, score in zip(frame['texts'], frame['scores']):
            print(f"    - {text} (confidence: {score:.2f})")
    
    if len(results["frames"]) > 5:
        print(f"\n... and {len(results['frames']) - 5} more frames")
    
    # Extract unique texts
    if args.extract_text:
        print("\n" + "=" * 60)
        print("All Unique Texts")
        print("=" * 60)
        all_texts = client.extract_text_from_video(args.video, args.sample_rate)
        for text in all_texts:
            print(f"  - {text}")
    
    # Save results to JSON
    output_json = Path(args.video).stem + "_results.json"
    with open(output_json, "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=2)
    print(f"\nResults saved to: {output_json}")


if __name__ == "__main__":
    main()

